<?php
/**
 * 后台管理员管理
 * User: t.young
 * Date: 2017/12/16
 * Time: 17:12
 */

namespace backend\modules\system\controllers;


use backend\component\BackendBaseController;
use backend\component\ResultFormat;
use backend\service\AdminService;
use common\component\ClassFactory;
use common\models\base\Admin;

class AdminController extends BackendBaseController
{
    public function actions()
    {
        return [
            "delete" =>[
                'class' => "backend\actions\DeleteAction",
                'modelName'=>Admin::className(),
                'is_physics' => true
            ],
            "modify" => [
                'class' => "backend\actions\ModifyAction",
                'modelName'=> Admin::className(),
            ],
            "swith" => [
                "class" => "backend\actions\SwithAction",
                "modelName" => Admin::className(),
                "field" => "status",
            ],
        ];
    }


    /**
     * 加载管理员视图
     */
    public function actionList()
    {
        if (\Yii::$app->request->getIsAjax()) {
            return AdminService::adminListData(\Yii::$app->request->post());
        }
        $model = ClassFactory::getInstance(Admin::className());
        return $this->render("list",['model'=>$model]);
    }

    /**
     * 加载编辑视图
     */
    public function actionEdit() {
        $id = \Yii::$app->request->get("id",0);
        $model = Admin::modelById($id);
        return $this->render("edit",['model'=>$model]);
    }

    /**
     * 角色分配
     * @return string
     */
    public function actionRole() {
        $user_id = \Yii::$app->request->get("id",0);
        $roles = AdminService::roleByUid($user_id);
        $model = Admin::modelById($user_id);
        return $this->render("role",["roles"=>$roles,"model"=>$model]);
    }

    /**
     * 角色保存
     */
    public function actionTorole() {
        $user_id = \Yii::$app->request->get("id");
        $role_arr = \Yii::$app->request->post("role");
        $result = AdminService::modifyUserToRole($user_id,$role_arr);
        if ($result) {
            return ResultFormat::success("操作成功");
        }
        return ResultFormat::error("操作失败,请联系管理人");
    }

    /**
     * 修改密码
     */
    public function actionModPwd() {
        if (\Yii::$app->request->getIsAjax() && isset($_POST['form'])) {
            $params = \Yii::$app->request->post("form");
            $user_id = \Yii::$app->request->get("id");
            return AdminService::modifyUserPassword($user_id,$params);
        }
        $user_id = \Yii::$app->request->get("id");
        $model = Admin::modelById($user_id);
        return $this->render("password",["model"=>$model]);
    }
}


